/*
 * Filename:    StandardscoreDaoServiceImpl.java
 * Copyright:   2014 中国平安保险（集团）股份有限公司 版权所有
 * Company:     平安科技养老险及健康险系统开发部
 * Create at:   2014年10月31日
 */
package com.paic.mhis.hcpms.agreement.healthcareprovider.biz.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.paic.mhis.common.base.intergration.dao.CommonDAO;
import com.paic.mhis.common.util.BusinessServiceUtil;
import com.paic.mhis.hcpms.agreement.healthcareprovider.biz.service.StandardscoreService;
import com.paic.mhis.hcpms.agreement.healthcareprovider.dto.StandardScoreDTO;
import com.paic.mhis.hcpms.agreement.healthcareprovider.util.Constants;
import com.paic.mhis.hcpms.agreement.healthcareprovider.util.StandardScoreConstants;
import com.paic.pafa.app.biz.service.BusinessServiceException;

@Service("standardscoreService")
public class StandardscoreServiceImpl implements StandardscoreService {

	@Autowired
	private CommonDAO commonDAO;

	private static final String FIRST_NODE = "1";

	private static final String SECOND_NODE = "2";

	private static final String THIRD_NODE = "3";

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public Map<String, Object> saveStandardScore(JSONArray transferJson,
			String loginName) throws BusinessServiceException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			List<StandardScoreDTO> slist = new ArrayList<StandardScoreDTO>();
			List<StandardScoreDTO> tlist = new ArrayList<StandardScoreDTO>();
			StringBuffer sbff = new StringBuffer();
			StandardScoreDTO firstNodeBean = new StandardScoreDTO();
			Map<String, String> uuidMap = new HashMap<String, String>();

			for (int i = 0; i < transferJson.size(); i++) {
				StandardScoreDTO dto = null;
				JSONObject tempJson = transferJson.getJSONObject(i);
				dto = JSONObject.toJavaObject(tempJson, StandardScoreDTO.class);
				if ("1".equals(dto.getIsValid())) {
					if (dto.getStandardscoreid() != null)
						sbff.append("'" + dto.getStandardscoreid() + "',");
					continue;
				}
				dto.setUpdatedBy(loginName);
				dto.setCreatedBy(loginName);
				toSaveDiffSecKinds(slist, tlist, dto, uuidMap, firstNodeBean);
			}
			String firstUuid = firstNodeBean.getStandardscoreid();
			// 获取当前总分
			Map<String, String> queryMap = new HashMap<String, String>();
			queryMap.put("id", firstUuid);
			queryMap.put("type", firstNodeBean.getScoreType());
			int value = (Integer) commonDAO.get(
					"standardScoreDao.queryTotalValue", queryMap);
			// 获取新增总分
			int otherValue = 0;
			for (StandardScoreDTO stdo : slist) {
				otherValue += stdo.getUpperValues().intValue();
			}

			if (!"1".equals(firstNodeBean.getScoreType())) {
				if (value + otherValue > 100) {
					resultMap.put(Constants.STATE_KEY,
							Constants.FAILED_VALIDATE_STATE_VALUE);
					resultMap.put(Constants.MSG_KEY, "总分超过100分，不能保存！");
					return resultMap;
				}
			}
			if (firstNodeBean.getIsNewScore() != null) {
				firstNodeBean.setScoreLevel(FIRST_NODE);
				commonDAO.insert("standardScoreDao.addStandardScore",
						firstNodeBean);
			} else {
				commonDAO.update("standardScoreDao.updateStandardScore",
						firstNodeBean);
			}
			// 第二层级
			for (StandardScoreDTO stdo : slist) {
				stdo.setParentid(firstUuid);
				stdo.setScoreLevel(SECOND_NODE);
				if (stdo.getIsNewScore() != null) {
					commonDAO.insert("standardScoreDao.addStandardScore", stdo);
				} else {
					commonDAO.insert("standardScoreDao.updateStandardScore",
							stdo);
				}
			}
			// 第三级
			for (StandardScoreDTO ttdo : tlist) {
				ttdo.setScoreLevel(THIRD_NODE);
				ttdo.setParentid(uuidMap.get(ttdo.getSecondNodeId()));
				if (ttdo.getIsNewScore() != null) {
					commonDAO.insert("standardScoreDao.addStandardScore", ttdo);
				} else {
					commonDAO.insert("standardScoreDao.updateStandardScore",
							ttdo);
				}
			}
			// 删除
			if (sbff.length() > 0) {
				deleteStandarScore(sbff, loginName);
			}
			resultMap.put(Constants.STATE_KEY, Constants.SUCCESS_STATE_VALUE);
			resultMap.put(Constants.MSG_KEY, Constants.SAVE_OR_UPDATE_SUCCESS);
		} catch (Exception e) {
			BusinessServiceUtil.processException(e);
			e.printStackTrace();
		}
		return resultMap;
	}

	/**
	 * 
	 * @param kinds
	 * @param toEqStr
	 * @param uuid
	 */
	private void toSaveDiffSecKinds(List<StandardScoreDTO> sKinds,
			List<StandardScoreDTO> tKinds, StandardScoreDTO toEqBean,
			Map<String, String> uuidMap, StandardScoreDTO fBean) {
		// 第三层级
		if (toEqBean.getThirdNodeId() != null) {
			if (toEqBean.getStandardscoreid() == null
					|| toEqBean.getStandardscoreid() != null
					&& toEqBean.getStandardscoreid().length() != 32) {
				toEqBean.setStandardscoreid(commonDAO.getUUID());
				toEqBean.setIsNewScore(true);
			}
			tKinds.add(toEqBean);// toEqBean.getThirdNodeId() != null
			return;
		}
		// 第一层级
		if (toEqBean.getSecondNodeId() == null
				&& toEqBean.getThirdNodeId() == null) {
			// 如果uuid不是32位的 说明是新增数据
			BeanUtils.copyProperties(toEqBean, fBean);
			if (toEqBean.getStandardscoreid() == null
					|| toEqBean.getStandardscoreid() != null
					&& toEqBean.getStandardscoreid().length() != 32) {
				fBean.setStandardscoreid(commonDAO.getUUID());
				fBean.setIsNewScore(true);
			}
			return;
		}
		// 第二层级
		for (StandardScoreDTO bean : sKinds) {
			// 遍历第二层级数据
			if (bean.getSecondNodeId().equals(toEqBean.getSecondNodeId()))
				return;
		}
		if (toEqBean.getStandardscoreid() == null
				|| toEqBean.getStandardscoreid() != null
				&& toEqBean.getStandardscoreid().length() != 32) {
			String uuidStr = commonDAO.getUUID();
			toEqBean.setStandardscoreid(uuidStr);
			toEqBean.setIsNewScore(true);
			uuidMap.put(toEqBean.getSecondNodeId(), uuidStr);
		} else {
			uuidMap.put(toEqBean.getSecondNodeId(), toEqBean.getSecondNodeId());
		}
		sKinds.add(toEqBean);
	}

	/**
	 * 
	 * @param sbff
	 * @param loginName
	 */
	private void deleteStandarScore(StringBuffer sbff, String loginName) {
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		String ids = sbff.toString().substring(0, sbff.toString().length() - 1);
		paramsMap.put("ids", ids);
		paramsMap.put("updatedBy", loginName);
		commonDAO.update("standardScoreDao.deleteStandardScore", paramsMap);
	}

	@Override
	public StandardScoreDTO findStandardScore(StandardScoreDTO dto) {
		StandardScoreDTO resultBean = new StandardScoreDTO();
		// 查询第一层
		StandardScoreDTO fparams = new StandardScoreDTO();
		fparams.setScoreType(dto.getScoreType());
		fparams.setScoreLevel(FIRST_NODE);
		List<StandardScoreDTO> firstNodeList = commonDAO.query(
				"standardScoreDao.findStandardScoreList", fparams);
		fparams = new StandardScoreDTO();
		fparams.setScoreType(dto.getScoreType());
		fparams.setScoreLevel(SECOND_NODE);
		List<StandardScoreDTO> secondNodeList = commonDAO.query(
				"standardScoreDao.findStandardScoreList", fparams);
		// 设置总分
		// 总分
		String type = dto.getScoreType();
		String codeNo = "";
		if (StandardScoreConstants.ORG_SCORE_TYPE.equals(type)) {
			codeNo = StandardScoreConstants.ORG_SCORE_CODENO;
		} else if (StandardScoreConstants.PERSON_SCRORE_TYPE.equals(type)) {
			codeNo = StandardScoreConstants.PERSON_SCRORE_CODENO;
		} else if (StandardScoreConstants.DRUGSTORE_SCORE_TYPE.equals(type)) {
			codeNo = StandardScoreConstants.DRUGSTORE_SCORE_CODENO;
		}
		Map params = new HashMap<String, String>();
		params.put("codeNo", codeNo);
		params.put("codeType", "standardTotalScore");
		String codeDesc = (String) commonDAO.get(
				"standardScoreDao.getTotalScore", params);
		int socreTemp = Integer.parseInt(codeDesc);
		BigDecimal totalScore = new BigDecimal(socreTemp);

		resultBean.setUpperValues(totalScore);
		fparams = new StandardScoreDTO();
		fparams.setScoreType(dto.getScoreType());
		fparams.setScoreLevel(THIRD_NODE);
		List<StandardScoreDTO> thirdNodeList = commonDAO.query(
				"standardScoreDao.findStandardScoreList", fparams);

		for (StandardScoreDTO sdto : secondNodeList) {
			List<StandardScoreDTO> tmpList = new ArrayList<StandardScoreDTO>();
			for (StandardScoreDTO tdto : thirdNodeList) {
				if (sdto.getStandardscoreid().equals(tdto.getParentid())) {
					tmpList.add(tdto);
				}
			}
			sdto.setDtoList(tmpList);
		}

		for (StandardScoreDTO fdto : firstNodeList) {
			BigDecimal score = BigDecimal.ZERO;
			List<StandardScoreDTO> tmpList = new ArrayList<StandardScoreDTO>();
			for (StandardScoreDTO sdto : secondNodeList) {
				if (fdto.getStandardscoreid().equals(sdto.getParentid())) {
					tmpList.add(sdto);
					BigDecimal tempScore = sdto.getUpperValues();
					if (tempScore == null) {
						tempScore = BigDecimal.ZERO;
					}
					score = score.add(tempScore);
				}
			}
			fdto.setUpperValues(score);
			fdto.setDtoList(tmpList);
		}
		resultBean.setDtoList(firstNodeList);
		return resultBean;
	}

	@Override
	public StandardScoreDTO findStandardScoreDetail(String standardscoreid) {
		// 查询第一层
		StandardScoreDTO fparams = new StandardScoreDTO();
		fparams.setStandardscoreid(standardscoreid);
		List<StandardScoreDTO> firstNodeList = commonDAO.query(
				"standardScoreDao.findStandardScoreList", fparams);
		fparams = new StandardScoreDTO();
		fparams.setParentid(standardscoreid);
		List<StandardScoreDTO> secondNodeList = commonDAO.query(
				"standardScoreDao.findStandardScoreList", fparams);
		fparams.setStandardscoreid(standardscoreid);
		List<StandardScoreDTO> thirdNodeList = commonDAO.query(
				"standardScoreDao.findStandardScore4Third", fparams);

		String MAIN_NODE_1 = "F_1";
		String MAIN_NODE_2 = "S_";
		String MAIN_NODE_3 = "T_";
		for (int i = 0; i < secondNodeList.size(); i++) {
			StandardScoreDTO sdto = secondNodeList.get(i);
			List<StandardScoreDTO> tmpList = new ArrayList<StandardScoreDTO>();
			int tNodeId = 0;
			for (int j = 0; j < thirdNodeList.size(); j++) {
				StandardScoreDTO tdto = thirdNodeList.get(j);
				if (sdto.getStandardscoreid().equals(tdto.getParentid())) {
					tdto.setFirstNodeId(MAIN_NODE_1);
					tdto.setSecondNodeId(MAIN_NODE_2 + i);
					tdto.setThirdNodeId(MAIN_NODE_3 + ++tNodeId);
					tmpList.add(tdto);
				}
			}
			sdto.setSecondNodeId(MAIN_NODE_2 + i);
			sdto.setFirstNodeId(MAIN_NODE_1);
			sdto.setDtoList(tmpList);
		}
		StandardScoreDTO fbeen = firstNodeList.get(0);
		fbeen.setDtoList(secondNodeList);
		fbeen.setFirstNodeId(MAIN_NODE_1);
		return fbeen;
	}

	/**
	 * 总分获得
	 * 
	 * @param list
	 * @return
	 */
	private BigDecimal getCountScore(List<StandardScoreDTO> list) {
		BigDecimal tmp = BigDecimal.ZERO;
		for (StandardScoreDTO sto : list) {
			if (sto.getUpperValues() != null)
				tmp = tmp.add(sto.getUpperValues());
		}
		return tmp;
	}

	@Override
	public Map<String, Object> deleteStandardScoreBySuperId(String superId,
			String loginName) throws BusinessServiceException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("standardscoreid", superId);
		resultMap.put("updatedBy", loginName);
		commonDAO.update("standardScoreDao.deleteStandardScoreBySuperId",
				resultMap);
		resultMap = new HashMap<String, Object>();
		resultMap.put(Constants.MSG_KEY, Constants.DELETE_SUCCESS);
		resultMap.put(Constants.STATE_KEY, Constants.SUCCESS_STATE_VALUE);
		return resultMap;
	}

	public StandardScoreDTO queryTotalValue(Map queryMap) {
		StandardScoreDTO resultBean = new StandardScoreDTO();
		return resultBean;
	}

}
